package edu.friday.dao.custom.impl;

import edu.friday.dao.custom.GenTableColumnCustomDAO;
import edu.friday.model.dto.GenTableColumnDTO;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import java.util.List;

public class GenTableColumnCustomDAOImpl implements GenTableColumnCustomDAO {

    @PersistenceContext
    private EntityManager entityManager;

    @Override
    public List<GenTableColumnDTO> selectDbTableColumnsByName(String tableName) {
        StringBuffer sql = new StringBuffer();
        sql.append(" select column_name ");
        sql.append(" ,(case when (is_nullable = 'no' and column_key != 'PRI') then '1' else null end) as is_required ");
        sql.append(" ,(case when column_key = 'PRI' then '1' else '0' end) as is_pk  ");
        sql.append(" ,ordinal_position as sort ");
        sql.append(" ,column_comment  ");
        sql.append(" ,(case when extra = 'auto_increment' then '1' else '0' end) as is_increment ");
        sql.append(" , column_type ");
        sql.append(" from information_schema.columns where table_schema = (select database()) and table_name = (:tableName) ");
        sql.append(" order by ordinal_position ");
        Query query = entityManager.createNativeQuery(sql.toString(), GenTableColumnDTO.class)
                .setParameter("tableName", tableName);
        return query.getResultList();
    }
}

